package com.hnas.core.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.Session;
import org.springframework.stereotype.Component;

/**
 * @author zybluesky
 * 
 *///extends JpaDaoSupport
@Component("baseDAO")
public class BaseHibernateDAO  implements
		IBaseHibernateDAO {

	@PersistenceContext(unitName="simple")
	  private EntityManager entityManager;   
	 
	public Session openSession() {	
//		return SessionFactoryUtils.getSession(getSessionFactory(), true);//
		return null;
	}
	
	public EntityManager getEntityManager(){
//		EntityManager em = this.getJpaTemplate().getEntityManagerFactory().createEntityManager();
		return this.entityManager;
	}

	public Object findByID(Class clazz, java.io.Serializable id) {
		return this.entityManager.find(clazz, id);
	}

	public void delete(Object o) {
//		 this.getJpaTemplate().remove(o);
		this.entityManager.remove(o);
	}	
	
	public Object saveOrUpdate(Object obj) {
//		this.getJpaTemplate().merge(obj);
		// this.getHibernateTemplate().flush();
//		 this.getJpaTemplate().persist(obj);
		this.entityManager.persist(obj);
		 return obj;
//		return this.getEntityManager().persist(obj);
	}

	public Object saveOrUpdatef(Object obj) {
//		this.getJpaTemplate().persist(obj);
//		this.getJpaTemplate().flush();
		return this.saveOrUpdate(obj);
	}

	public Collection saveOrUpdateAll(Collection c) {
//		this.getJpaTemplate().saveOrUpdateAll(c);
		// this.getHibernateTemplate().flush();
		List ls = new ArrayList();
		for (Iterator it = c.iterator();it.hasNext();){
			ls.add(this.saveOrUpdate(it.next()));
		}
		return ls;
	}

	public void update(Object obj){
//		this.getJpaTemplate().merge(obj);
		this.entityManager.merge(obj);
	}
	public void updateAll(Collection c){
		for (Iterator it = c.iterator();it.hasNext();){
			this.update(it.next());
		}
	}

	//���hql��䷵�ؽ���б�
	public List getList(String hql, Object ob2[]){
		List ls ;//= new ArrayList();
//		ls = this.getJpaTemplate().find(hql, ob2);
		EntityManager em = getEntityManager();//getJpaTemplate().getEntityManager();
//		Session session = getSession(false);
//		Query q = session.createQuery(hql);
		Query q = em.createQuery(hql);
		if (null != ob2) {
			for (int i = 0; i < ob2.length; i++) {
				q.setParameter(i, ob2[i]);
			}
		}
		return q.getResultList();
		
	}
	
	
	
	public int getTotalCount(String hql, Object ob2[]) {
//System.out.println(hql);
		int index_from = hql.indexOf("from");
		if (index_from >= 0)
			hql = hql.substring(index_from);
		
		int index_order = hql.lastIndexOf("order by");		
		if (index_order >= 0)
			hql = hql.substring(0, index_order);

		int join = hql.indexOf("inner join");
		if (join>0){
			//ȥ��
			int where = hql.indexOf("where");			
			hql=hql.substring(0,join)+(where>0?hql.substring(where):"");
		}		
		
		hql = "select count(*) " + hql;

		EntityManager em = getEntityManager();//getJpaTemplate().getEntityManager();
//		Session session = getSession(false);
//		Query q = session.createQuery(hql);
		Query q = em.createQuery(hql);
		if (null != ob2) {
			for (int i = 0; i < ob2.length; i++) {
				q.setParameter(i, ob2[i]);
			}
		}

		Object o = q.getSingleResult();
		if (null == o)
			return 0;
		// return ((Integer)o).intValue();
		return Integer.parseInt(o.toString());
		// List list = q.list();
		// int count = 0;
		// if (list.size() > 0) {
		// count = ((Integer) list.get(0)).intValue();
		// }
		// return count;
	}

	/*
	 * public List getList(String hql, Object ob2[], int firstRow, int maxRows) {
	 * Session session = getSession(false); Query q = session.createQuery(hql);
	 * if (null!=ob2){ for (int i = 0; i < ob2.length; i++) { q.setParameter(i,
	 * ob2[i]); } } q.setFirstResult(firstRow); q.setMaxResults(maxRows); return
	 * q.list(); }
	 */
	//
	public List getList(String hql, Object ob2[], int firstRow, int maxRows) {
		Query queryObject = entityManager.createQuery(hql);
		int i = 0;
		for(Object obj : ob2) {
			queryObject.setParameter(i++, obj);
		}
		if (firstRow>0){
			queryObject.setFirstResult(firstRow);
		}
		if (maxRows > 0) {
			queryObject.setMaxResults(maxRows);
		}
		return queryObject.getResultList();
	}

	public void queryByPage(PageBean page, String hql, Object[] paras) {
		// ��ҳ��ѯ
		// ��ѯ���--��ҳ
		// ����ҳ��
		// String hql = page.getListSQL();
		int firstRow = (page.getPage() - 1) * page.getPageSize();
		if (firstRow < 0) {
			firstRow = 0;
			page.setPage(1);
		}
		int maxRows = page.getPageSize();
		if (maxRows <= 0) {
			maxRows = 20;
			page.setPageSize(20);
		}

		List contents = this.getList(hql, paras, firstRow, maxRows);

		page.setContents(contents);
		if (page.getCount() < 0) {// ���û���ܼ�¼��
			// ��ȡ�ܼ�¼��
			int count = this.getTotalCount(hql, paras);

			page.setCount(count);
		} else {
			page.setCount(page.getCount());// ����ҳ��
		}

	}


	

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}	

//	public List getList(String)
	
//	public Object initial(Object o){
//		this.getHibernateTemplate().initialize(o);
//	}
}
